from django.shortcuts import render
from django.contrib.auth import authenticate,login
from django.contrib.auth.backends import ModelBackend
from .models import UserProfile,EmailVerifyRecord
from django.db.models import Q #可以完成并操作
from django.views.generic.base import View#继承该类，完成功能
from .forms import LoginForm,RegisterForm,ForgetForm,ModifyForm
from django.contrib.auth.hashers import make_password#对明文进行加密
from utils.email_send import send_register_email
from django.http import  HttpResponse
class CustomBackend(ModelBackend):
    """
    自定义的方法
    """
    #函数重载
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            #查询一下user是否存在
            user=UserProfile.objects.get(Q(username=username)|Q(email=username))#并集查询，可以通过邮箱和账号一起登录。
            if user.check_password(password):#把明文加密。并与数据库的密文比对
                return user
        except Exception as e :
            return None

# Create your views here.


# class LoginView(View):
#     """
#     基于类的一种书写。重写了get，post方法。
#     """
#
#
#     #重载get方法
#     def get(self,request):
#         return render(request, 'login.html', locals())
#     def post(self,request):
#         user_name = request.POST['username']
#         pass_word = request.POST['password']
#         print(user_name, pass_word)
#         user = authenticate(username=user_name, password=pass_word)
#         if user is not None:
#             login(request, user)
#             return render(request, 'index.html')
#         else:
#             return render(request, 'login.html', {"msg": "用户密码或账户错误"})
class ActiveUserView(View):
    """
    完成用户的激活
    """


    def get(self,request,active_code):
        all_records=EmailVerifyRecord.objects.filter(code=active_code)
        if all_records:#如果有记录
            for records in all_records:
                email=records.email #先查到邮箱
                user=UserProfile.objects.get(email=email)#查到用户
                user.is_active=True
                user.save()
        else:#如果验证码找不到。
            return HttpResponse("链接失效")
        return render(request,'login.html')

class RegisterView(View):
    def get(self,request):
        register_form=RegisterForm()
        return render(request,'register.html',{'register_form':register_form})

    def post(self,request):
        register_form = RegisterForm(request.POST)
        if register_form.is_valid():
            user_name=request.POST['email']

            if UserProfile.objects.filter(email=user_name):#如果用户名已经存在
                return render(request,'register.html',{"register_form":register_form,"msg":"用户已经存在"})
            pass_word=request.POST['password']

            user_profile=UserProfile()#定义一个实例，然后存数据库。
            user_profile.username=user_name
            user_profile.email=user_name
            user_profile.is_active=False #用户还未激活
            user_profile.password=make_password(pass_word)
            user_profile.save()

            send_register_email(user_name,'register')
            return render(request, 'login.html')
        else:
            return render(request, 'register.html',{"register_form":register_form})

class LoginView(View):
    """
    基于类的一种书写。重写了get，post方法。
    """


    #重载get方法
    def get(self,request):
        return render(request, 'login.html', locals())
    def post(self,request):
        login_form=LoginForm(request.POST)#需要传进来一个字典

        if login_form.is_valid():#验证成功

            user_name = request.POST['username']
            pass_word = request.POST['password']
            print(user_name, pass_word)
            user = authenticate(username=user_name, password=pass_word)
            if user is not None:
                if user.is_active:
                    login(request, user)
                    return render(request, 'index.html')
                else:
                    return render(request, 'login.html', {"msg": "用户未激活"})
            else:#表单格式没有问题，但是数据有问题的情况
                return render(request, 'login.html', {"msg":"用户名或密码错误"})
        else:#表单验证未通过
            return render(request, 'login.html', {"login_form":login_form})


#
# def user_login(request):
#     """
#     基于函数的一种方法
#     :param request:
#     :return:
#     """
#     if request.method=='POST':
#         user_name=request.POST['username']
#         pass_word=request.POST['password']
#         print(user_name,pass_word)
#         user=authenticate(username=user_name,password=pass_word)
#         if user is not  None:
#
#             login(request,user)
#             return render(request,'index.html')
#         else:
#             return render(request, 'login.html', {"msg":"用户密码或账户错误"})
#
#     elif request.method=='GET':
#         return render(request,'login.html',locals())

class ForgetView(View):
    def get(self,request):
        forget_form=ForgetForm()
        return render(request,'forgetpwd.html',locals())

    def post(self,request):
        forget_form=ForgetForm(request.POST)
        if forget_form.is_valid():
            email=request.POST['email']
            send_register_email(email,'forget')
            return HttpResponse("邮件发送成功")
        else:#表单验证失败
            return render(request, 'forgetpwd.html', locals())

class ResetView(View):
    """
    完成用户的激活
    """


    def get(self,request,active_code):
        all_records=EmailVerifyRecord.objects.filter(code=active_code)
        if all_records:#如果有记录
            for records in all_records:
                email=records.email #先查到邮箱
                return render(request,'password_reset.html',{'email':email})
        else:#如果验证码找不到。
            return HttpResponse("链接失效")
        return render(request,'login.html')

    def post(self,request):
        modify_form=ModifyForm(request.POST)
        if modify_form.is_valid():
            pwd1=request.POST['password1']
            pwd2=request.POST['password2']
            email=request.POST['email']
            if(pwd1!=pwd2):#不相等，返回错误。
                return render(request, 'password_reset.html', {'email': email,'msg':'密码不一致'})
            user=UserProfile.objects.get(email=email)
            user.password=make_password(pwd1)
            user.save()#完成了密码修改。
            return render(request,'login.html')#返回登录页面

        else:
            email = request.POST['email']
            return render(request, 'password_reset.html', {'email': email,  'modify_form':modify_form})

